# -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from datetime import datetime


class HtmlMeta(models.Model):
    html_title = models.CharField(verbose_name = _(u'Meta Title <title>'), max_length = 150, blank = True, null = True)
    html_description = models.CharField(verbose_name = _(u'Meta Description'), max_length = 200, blank = True, null = True)
    html_keywords = models.CharField(verbose_name = _(u'Meta Keywords'), max_length = 120, blank = True, null = True)
    
    class Meta:
        abstract = True
    
    
class DateMeta(models.Model):
    created = models.DateTimeField(verbose_name = _(u'Erstellungsdatum'), default = datetime.now)
    modified = models.DateTimeField(verbose_name = _(u'Änderungsdatum'), default = datetime.now)
    
    class Meta:
        abstract = True
        
    # TODO: implement signal
    # everytime an entry will be updated, modified field must be updated too
    
    
# http://djangosnippets.org/snippets/1271/
class CloneableMixin(object):
    def _clone_copy(self):
        import copy
        """ Return an identical copy of the instance with a new ID. """
        if not self.pk:
            raise ValueError('Instance must be saved before it can be cloned.')
        return copy.copy(self)
        
    def _clone_prepare(self, duplicate):
        # Setting pk to None tricks Django into thinking this is a new object.
        duplicate.pk = None
        
    def _clone_save(self, duplicate):
        duplicate.save(force_insert = True)
        
    def _clone_copy_m2m(self, duplicate):
        # ... but the trick loses all ManyToMany relations.
        for field in self._meta.many_to_many:
            objs = getattr(self, field.attname).all()
            setattr(duplicate, field.attname, objs)
            
    def _clone_copy_reverse_m2m(self, duplicate):
        for relation in self._meta.get_all_related_many_to_many_objects():
            objs = getattr(self, relation.field.rel.related_name).all()
            setattr(duplicate, relation.field.rel.related_name, objs)
            
    def clone(self):
        duplicate = self._clone_copy()
        self._clone_prepare(duplicate)
        self._clone_save(duplicate)
        self._clone_copy_m2m(duplicate)
        self._clone_copy_reverse_m2m(duplicate)
        return duplicate
        
        
class StatCloneableMixin(CloneableMixin):
    def _clone_prepare(self, duplicate):
        super(StatCloneableMixin, self)._clone_prepare(duplicate)
        duplicate.created = datetime.now()
        
